<template>

  <div>
    <Layout>
      <Content class="layout-content">

        <Row>
          <Col span="1.5">
            开始日期：
          </Col>
          <Col span="3">
            <DatePicker type="date" v-model="startDate" placeholder="请选择日期" style="width: 150px"
                        @on-change="changeDateScheduleDeptList"/>
          </Col>
          <Col span="1.5">
            结束日期：
          </Col>
          <Col span="3">
            <DatePicker type="date" v-model="endDate" placeholder="请选择日期" style="width: 150px"
                        @on-change="changeDateScheduleDeptList"/>
          </Col>
          <Col span="4">
            <Select v-model="locIds" filterable @on-query-change="locSearchs" :max-tag-count="1" clearable multiple
                    size="default">
              <Option v-for="item in locIdList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>

          </Col>

          <Col span="3">
            <Input v-model="keywords" placeholder="请输入患者姓名或老系统预约记录ID"/>
          </Col>

          <Col span="2">
            &nbsp;
            <Button type="primary" @click="appointmentSchedule">预约排班</Button>
          </Col>
          <Col span="2">
            日志:
            <Switch v-model="logViewFlag"/>
          </Col>
        </Row>
        <Row>
          <Col span="24">
            <div style="overflow-x: scroll">
              <Table :columns="columns" draggable :data="data" stripe border :height="tableHeight"></Table>
            </div>
          </Col>
        </Row>
        <Divider/>
        <Row>
          <Col span="8" style="margin-right: 10px;">
            <Row style="border: 1px solid #cccccc">
              <Col span="9">
                <Button type="primary" @click="dateRangeSync()">同步排班记录</Button>
              </Col>
              <!--              <Col span="10">-->
              <!--                <Button type="primary" @click="continueSync()">继续同步排班记录</Button>-->
              <!--              </Col>-->
              <Col span="10">
                <Checkbox v-model="syncAppointmentFlag">同步预约记录</Checkbox>
              </Col>
            </Row>
          </Col>

          <Col span="8" style="margin-right: 10px;">
            <Row>

              <Col span="12">
                <Button type="primary" @click="nowSyncAppointment()">同步预约记录</Button>
              </Col>
              <Col span="12">
                <Button type="primary" @click="continueSyncAppointment">继续同步预约记录</Button>
              </Col>
            </Row>
          </Col>

          <!--          <Col span="12">-->
          <!--          </Col>-->
        </Row>

        <Drawer title="日志查看" :mask="false" :closable="true" :width="400" :z-index="9999" :draggable="true"
                v-model="logViewFlag">
          <LogView></LogView>
        </Drawer>

      </Content>
    </Layout>

  </div>


</template>
<script setup>
import {onMounted, ref, toRaw, inject, getCurrentInstance} from "vue";
import api from '../request/apis'
import moment from "moment";
import {Message, Row} from 'view-ui-plus'
import {locSync, locAppointmentSync} from './locSync/LocSync.js'
import LogView from "./logview/LogView.vue";
import {nextTick, debounce} from '../utils'
import {clear, info} from "./logview/index.js";
import _ from "lodash";

const logViewFlag = ref(true);
const tableHeight = ref(400);

const syncAppointmentFlag = ref(false);

const locSearchs = (key) => {
  if (key === 'all') {
    locIds.value = [];
    for (var ib in locIdList.value) {
      var cs = locIdList.value[ib];
      locIds.value.push(cs.value);
    }
  } else if (key == 'clear') {
    locIds.value = [];
  }
}
//默认儿科
const locIds = ref([]);

const doctorIds = ref([]);

const keywords = ref();
// select '{ value:'||l.CTLOC_RowID||',label:'''|| l.CTLOC_Desc||'''},' from SQLUser.CT_Loc l
// where l.CTLOC_RowID in (
//     select distinct r.RES_CTLOC_DR
// from SQLUser.RB_ApptSchedule s
// inner join SQLUser.RB_Resource r on RES_RowId = s.AS_RES_ParRef
// inner join SQLUser.CT_Loc l on l.CTLOC_RowID = r.RES_CTLOC_DR
// where s.AS_Date >= cast('2023-12-04' as DATE)
// and s.AS_Date <= cast('2023-12-04' as DATE)
// )
const locIdList = ref([])

const columns = ref([
  {
    title: '服务日期',
    key: 'serviceDate',
    tooltip: true,
    width: 120,
    resizable: true,
    fixed: 'left'

  },
  {
    title: '科室名称',
    key: 'locName',
    tooltip: true,
    width: 150,
    resizable: true,
    fixed: 'left'

  },
  {
    title: '医生',
    key: 'userName',
    tooltip: true,
    width: 150,
    resizable: true,
    fixed: 'left'

  },
  {
    title: '职称',
    key: 'jobTitle',
    tooltip: true,
    width: 150,
    resizable: true,
    fixed: 'left'
  },
  {
    title: '出诊级别',
    key: 'sessDesc',
    tooltip: true,
    width: 180,
    resizable: true,
    fixed: 'left'

  },
  {
    title: '班次',
    key: 'shiftName',
    tooltip: true,
    width: 100,
    resizable: true,
    fixed: 'left'

  },

  {
    title: '出诊开始日期',
    key: 'trStartTime',
    tooltip: true,
    width: 150,
    resizable: true

  },
  {
    title: '出诊结束日期',
    key: 'trEndTIme',
    tooltip: true,
    width: 150,
    resizable: true

  },
  {
    title: '预约限额',
    key: 'appLoad',
    ellipsis: true,
    width: 100,
    resizable: true
  },
  {
    title: '可预约数量',
    key: 'noApptSession',
    width: 100,
    tooltip: true,
    resizable: true

  },
  {
    title: '正号限额',
    key: 'numberOfRegisteredMail',
    tooltip: true,
    width: 100,
    resizable: true

  },

  {
    title: '挂号数量',
    key: 'trRegNum',
    tooltip: true,
    width: 100,
    resizable: true

  },
  {
    title: '时间间隔',
    key: 'trLength',
    tooltip: true,
    width: 150,
    resizable: true

  },
  {
    title: '排班时间信息',
    key: 'trRegInfoStr',
    tooltip: true,
    width: 150,
    resizable: true
  },
  {
    title: '排班号段信息',
    key: 'trRegNumStr',
    tooltip: true,
    width: 150,
    resizable: true
  }
]);
const startDate = ref(new Date(moment().add(1, 'days').format("YYYY-MM-DD")));

const endDate = ref(new Date(moment().add(1, 'days').format("YYYY-MM-DD")));

const data = ref([]);

const init = () => {
  logViewFlag.value = false;
}

const syncLocInfo = ref(["17"]);

const syncAppointmentLocInfo = ref([]);

const continueSync = async () => {
  await nowSync(JSON.parse(JSON.stringify(toRaw(syncLocInfo.value))));
}


const dateRangeSync = async (startDateStr, endDateStr) => {

  // startDate
  // endDate
  if (!startDateStr) {
    startDateStr = moment(startDate.value).format("YYYY-MM-DD");
  }

  if (!endDateStr) {
    endDateStr = moment(endDate.value).format("YYYY-MM-DD");
  }

  const b = locIds.value.length <= 0;
  if (b) {
    //先加载一把科室
    await loadAppScheduleDeptList(startDateStr, startDateStr);

    locSearchs('clear');

    locSearchs("all");
  }


  await nowSync(null, startDateStr, startDateStr);

  //不是当天的
  if (startDateStr != endDateStr) {
    //产生了跨度，需要一天一天的同步
    const rangeDateStr = moment(startDateStr).add(1, 'days').format("YYYY-MM-DD");
    if (b) {
      locSearchs('clear');
    }
    await dateRangeSync(rangeDateStr, endDateStr);
  }
}

const nowSync = async (locInfo, startDateStr, endDateStr) => {

  if (!locIds.value || locIds.value.length <= 0) {
    Message.info("请选择科室！");
    return;
  }
  api.clearCache();
  syncLocInfo.value = [];
  const date = moment();
  const syncStartDateStr = moment(date).format('YYYY-MM-DD HH:MM:SS');
  logViewFlag.value = true;
  clear();
  info(`同步开始,时间${syncStartDateStr}`);
  info(`总共要同步${locIds.value.length}个科室`);

  let i = 0;
  for (const locIdKey in locIds.value) {
    const locId = locIds.value[locIdKey];
    i++;
    if (locInfo && locInfo.length > 0) {
      const findFlag = _.indexOf(locInfo, locId + "");
      if (findFlag != -1) {
        info(`科室[${locId}]已经处理过了，跳过处理。进度(${i}/${locIds.value.length})`);
        syncLocInfo.value.push(locId + "");
        continue;
      }
    }

    const appScheduleList = await getAppList(locId, startDateStr, endDateStr);
    if (!appScheduleList || appScheduleList.length <= 0) {
      continue;
    }
    info(`现在同步科室${locId},进度(${i}/${locIds.value.length})`);
    await locSync(toRaw(appScheduleList));
    info(`同步科室${locId}结束,进度(${i}/${locIds.value.length})`);
    syncLocInfo.value.push(locId + "");
  }
  let endTime = moment();
  const syncEndDateStr = moment(endTime).format('YYYY-MM-DD HH:MM:SS');
  info(`同步结束，开始时间：${syncStartDateStr},结束时间${syncEndDateStr},
  日期${startDateStr}至${endDateStr},耗时${endTime.diff(date)}ms`)

  if (syncAppointmentFlag.value) {
    await nowSyncAppointment(null, startDateStr, endDateStr);
  }
}
const continueSyncAppointment = async () => {
  await nowSyncAppointment(JSON.parse(JSON.stringify(toRaw(syncAppointmentLocInfo.value))));

}
const nowSyncAppointment = async (locInfo, startDateStr, endDateStr) => {
  if (!locIds.value || locIds.value.length <= 0) {
    Message.info("请选择科室！");
    return;
  }

  api.clearCache();
  syncAppointmentLocInfo.value = [];
  const date = moment();
  const syncStartDateStr = moment(date).format('YYYY-MM-DD HH:MM:SS');
  logViewFlag.value = true;
  clear();
  info(`同步开始,时间${syncStartDateStr}`);
  info(`总共要同步${locIds.value.length}个科室`);

  let i = 0;
  for (const locIdKey in locIds.value) {
    const locId = locIds.value[locIdKey];
    i++;
    if (locInfo && locInfo.length > 0) {
      const findFlag = _.indexOf(locInfo, locId);
      if (findFlag != -1) {
        info(`科室[${locId}]已经处理过了，跳过处理。进度(${i}/${locIds.value.length})`);
        syncAppointmentLocInfo.value.push(locId + "");
        continue;
      }
    }

    const appScheduleList = await getAppList(locId, startDateStr, endDateStr);
    if (!appScheduleList || appScheduleList.length <= 0) {
      continue;
    }

    info(`现在同步科室${locId},进度(${i}/${locIds.value.length})`);
    await locAppointmentSync(toRaw(appScheduleList), keywords.value);
    info(`同步科室${locId}结束,进度(${i}/${locIds.value.length})`);
    syncAppointmentLocInfo.value.push(locId + "");
  }
  let endTime = moment();
  const syncEndDateStr = moment(endTime).format('YYYY-MM-DD HH:MM:SS');


  const startSs = startDateStr || moment(startDate.value).format("YYYY-MM-DD");
  const endSs = endDateStr || moment(endDate.value).format("YYYY-MM-DD");

  info(`同步结束，开始时间：${syncStartDateStr},结束时间${syncEndDateStr},
  日期${startSs}至${endSs},耗时${endTime.diff(date)}ms`)
}


const appointmentSchedule = async () => {

  if (!locIds.value || locIds.value.length <= 0) {
    Message.info("请选择科室！");
    return;
  }
  data.value = [];
  for (const bi in locIds.value) {
    const appScheduleList = await getAppList(locIds.value[bi]);
    if (appScheduleList) {
      for (const ib in appScheduleList) {
        data.value.push(appScheduleList[ib]);
      }
    }
  }
}


const getAppList = async (locId, startDateStr, endDateStr) => {
  const json = {
    startDate: startDateStr || moment(startDate.value).format("YYYY-MM-DD"),
    endDate: endDateStr || moment(endDate.value).format("YYYY-MM-DD"),
    "locIds": [locId],
    "docIds": doctorIds.value
  }
  //先获取后台数据
  const appScheduleList = await api.getAppScheduleList(json);
  return appScheduleList;
}

const changeDateScheduleDeptList = async () => {
  locSearchs('clear');
  await loadAppScheduleDeptList();
}

const loadAppScheduleDeptList = async (startDateStr, endDateStr) => {

  if (endDateStr == 'date') {
    endDateStr = null;
  }
  const json = {
    startDate: startDateStr || moment(startDate.value).format("YYYY-MM-DD"),
    endDate: endDateStr || moment(endDate.value).format("YYYY-MM-DD")
  }
  //先获取后台数据
  const appScheduleList = await api.getAppScheduleDeptList(json);

  locIdList.value = [];
  for (let appt of appScheduleList) {

    locIdList.value.push({
      value: appt.locid,
      label: appt.loccode
    })
  }
}

onMounted(() => {
  init();
  loadAppScheduleDeptList();
  setTableHeight();

  window.addEventListener("resize", function () {
    setTableHeight();
  })
})

const setTableHeight = () => {
  const d = window.innerHeight - 140;
  tableHeight.value = d;
}
//

</script>
<style scoped>
</style>